package com.example.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Date 2022/10/22
 * @Author Jonathan
 */
public class MyNettyClient1 {

    private static final Logger log = LoggerFactory.getLogger(MyNettyClient1.class);

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel channel) throws Exception {
                channel.pipeline().addLast(new LoggingHandler());
                channel.pipeline().addLast(new StringEncoder());
            }
        });

        // 起了一个新的线程，用于连接
        ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(8080));
        channelFuture.sync();
        Channel channel = channelFuture.channel();
        channel.writeAndFlush("hello world");
        log.info("消息发送成功");
        //eventExecutors.shutdownGracefully(); // 优雅的关掉线程池
        ChannelFuture closeFuture = channel.close();// 关闭channel是异步的
        // 两种办法 一是同步等待  二是增加回调
        closeFuture.sync();
//        closeFuture.addListener(future -> {
//            log.info("-_-");
//        });
        log.info("执行完close之后的一些后续工作");
        // 关了channel之后 还是一些线程在运行
        // 所有的线程都结束处理之后 才会关闭client
        eventExecutors.shutdownGracefully();
    }
}

